package com.ricchieri.lazymodel;

import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.filter.EmailToSendFilter;
import com.ricchieri.model.EmailToSend;
import com.ricchieri.service.interf.IEmailToSendService;

public class EmailToSendLazyDataModel extends LazyDataModel<EmailToSend> {

	private static final long serialVersionUID = 4593253494642335825L;

	private List<EmailToSend> emailToSends;
	private IEmailToSendService emailToSendService;
	private EmailToSendFilter emailToSendFilter;
	
	public EmailToSendLazyDataModel(IEmailToSendService emailToSendService, EmailToSendFilter emailToSendFilter) {
		super();
		this.emailToSendFilter = emailToSendFilter;
		this.emailToSendService = emailToSendService;
	}
	
    @Override
    public Object getRowKey(EmailToSend emailToSend) {
        return emailToSend.getId();
    }

    @Override
    public EmailToSend getRowData(String emailToSendId) {
        int id = Integer.valueOf(emailToSendId);

        for (EmailToSend emailToSend : emailToSends) {
            if(id == emailToSend.getId()) {
                return emailToSend;
            }
        }
        return null;
    }
    
	@Override
	public List<EmailToSend> load(int startingAt, int maxPerPage, String sortField, 
			SortOrder sortOrder, Map<String, String> filters) {
		
		emailToSendFilter.setSortField(sortField);
		emailToSendFilter.setSortOrder(sortOrder.toString());
		
        if(getRowCount() <= 0) {
            setRowCount(getEmailToSendService().getAllEmailToSendPaginatedCountByFilter(emailToSendFilter));
        }
        
        if(getRowCount() == startingAt && getRowCount()  != 0) {
        	startingAt = startingAt - BusinessSettings.ROW_MAX_RESULT;
        }
        emailToSends = getEmailToSendService().getAllEmailToSendPaginatedByFilter(emailToSendFilter, startingAt);

        setPageSize(BusinessSettings.ROW_MAX_RESULT);
        
        return emailToSends;
	}

	public List<EmailToSend> getEmailToSends() {
		return emailToSends;
	}

	public void setEmailToSends(List<EmailToSend> emailToSends) {
		this.emailToSends = emailToSends;
	}

	public IEmailToSendService getEmailToSendService() {
		return emailToSendService;
	}

	public void setEmailToSendService(IEmailToSendService emailToSendService) {
		this.emailToSendService = emailToSendService;
	}

	public EmailToSendFilter getEmailToSendFilter() {
		return emailToSendFilter;
	}

	public void setEmailToSendFilter(EmailToSendFilter emailToSendFilter) {
		this.emailToSendFilter = emailToSendFilter;
	}
}
